package com.gateway.controller

import com.alibaba.csp.sentinel.EntryType
import com.alibaba.csp.sentinel.annotation.SentinelResource
import com.alibaba.csp.sentinel.slots.block.RuleConstant
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowItem
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager
import com.yfree.global.YController
import org.springframework.cloud.context.config.annotation.RefreshScope
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestMethod
import org.springframework.web.bind.annotation.RestController

@RefreshScope
@RestController
//@CrossOrigin //已开启全局允许跨域，此处不再需要单独开放
class Controller_Gateway : YController() {
    init {
        //加载单接口热点流控规则
        ParamFlowRuleManager.loadRules(
            listOf(
                ParamFlowRule("indexParam").setParamIdx(0).setGrade(RuleConstant.FLOW_GRADE_QPS).setCount(1.0)
                    .setParamFlowItemList(
                        listOf( //例外值
                            ParamFlowItem("YFree", 10, "string")
                        )
                    )
            )
        )
    }

    //单接口QPS流控，common规则配置在nacos中做持久化
    @SentinelResource(value = "common", fallback = "yfree_defaultFallback", blockHandler = "yfree_defaultBlockHandle")
    @RequestMapping("/index", method = [RequestMethod.GET])
    fun index() = yResult()

    //单接口热点流控
    @SentinelResource(value = "indexParam", entryType = EntryType.IN, fallback = "indexParamFallback")
    @RequestMapping("/indexParam", method = [RequestMethod.GET])
    fun indexParam(param: String) = yResult(message = "success,param=$param")
    fun indexParamFallback(param: String): String = yResult(code = -1, message = "热词限流：indexParamFallback")
}
